package app.client.netant;

import java.net.URL;
import java.nio.charset.Charset;

import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

/**
 * 网络浏览器
 * @author JiaJ
 * @date 2018年1月22日
 *
 */
public class NetBrowser {
	
	/**
	 * 设置执行时间
	 */
	private int excuteTime = 2000;
	
	/**
	 * 网址信息
	 */
	private String url;
	
	/**
	 * 客户端
	 */
	private WebClient webClient;
	
	private boolean isCharset = true;
	
	/**
	 * 构造对象并设置网站
	 * @param url
	 */
	public NetBrowser(String url){
		this.url = url;
	}
	
	/**
	 * 设置JS延时时间
	 * @param time
	 */
	public void setExcuteTime(int time){
		this.excuteTime = time;
	}
	
	/**
	 * 设置编码
	 * @param isCharset
	 */
	public void setCharset(boolean isCharset){
		this.isCharset = isCharset;
	}
	
	/**
	 * 获取全部HTML信息
	 * @return
	 * @throws Exception
	 */
	public String getHTML(){
		
		String html = "";
		
		try {
			
			//构造一个webClient 模拟Chrome 浏览器
			this.webClient = new WebClient(BrowserVersion.CHROME);
			
			//this.webClient = new WebClient(BrowserVersion.FIREFOX_45,"218.106.205.145",8080);
			
			//屏蔽日志信息
			LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
			Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);		
			
			//支持JavaScript
			webClient.getOptions().setJavaScriptEnabled(true);
			webClient.getOptions().setCssEnabled(false);
			webClient.getOptions().setActiveXNative(false);
			webClient.getOptions().setCssEnabled(false);
			webClient.getOptions().setThrowExceptionOnScriptError(false);
			webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
			webClient.getOptions().setTimeout(5000);
			
			if(url.startsWith("https")){
				webClient.getOptions().setUseInsecureSSL(true);
			}
			
			HtmlPage rootPage = null;
			if(!this.isCharset){
				URL path = new URL(url);
				WebRequest webRequest = new WebRequest(path, HttpMethod.GET);
				webRequest.setCharset(Charset.forName("UTF-8"));
				rootPage = webClient.getPage(webRequest);
			}else{
				rootPage = webClient.getPage(this.url);
			}
						
			//设置一个运行JavaScript的时间
			webClient.waitForBackgroundJavaScript(this.excuteTime);
			html = rootPage.asXml();
			
			this.free();
			
		} catch (Exception e) {
			e.printStackTrace();
			
			throw new RuntimeException("获取网页信息失败！");
		}
		
		return html;
	}
	
	public void free(){
		if(this.webClient != null){
			this.webClient.close();
			System.gc();
		}	
	}
	
}
